{% extends "base.html" %}

{% block content %}
<style>
/* 液态玻璃效果样式 */
.page-header {
    background: var(--glass-bg);
    backdrop-filter: var(--glass-blur);
    -webkit-backdrop-filter: var(--glass-blur);
    border: 1px solid var(--glass-border);
    border-radius: var(--border-radius);
    padding: 2rem;
    margin-bottom: 2rem;
    box-shadow: var(--glass-shadow);
}

/* 液态玻璃卡片 */
.card {
    background: var(--glass-bg) !important;
    backdrop-filter: var(--glass-blur) !important;
    -webkit-backdrop-filter: var(--glass-blur) !important;
    border: 1px solid var(--glass-border) !important;
    border-radius: var(--border-radius) !important;
    box-shadow: var(--glass-shadow) !important;
    transition: var(--transition) !important;
    position: relative;
    overflow: hidden;
}

.card::before {
    content: '';
    position: absolute;
    top: 0;
    left: 0;
    right: 0;
    bottom: 0;
    background: linear-gradient(135deg, rgba(255, 255, 255, 0.1) 0%, rgba(255, 255, 255, 0.05) 100%);
    pointer-events: none;
    z-index: 0;
}

.card:hover {
    transform: translateY(-5px);
    box-shadow: 0 16px 48px rgba(0, 0, 0, 0.2) !important;
}

.card-body, .card-header {
    position: relative;
    z-index: 1;
}

/* 液态玻璃表格 */
.table {
    background: transparent !important;
    color: #1C1C1E !important;
}

.table thead th {
    background: var(--glass-bg) !important;
    backdrop-filter: var(--glass-blur) !important;
    -webkit-backdrop-filter: var(--glass-blur) !important;
    border-color: var(--glass-border) !important;
    color: #1C1C1E !important;
    font-weight: 600 !important;
    border-bottom: 2px solid var(--glass-border) !important;
    position: relative;
    overflow: hidden;
    z-index: 1;
}

.table thead th::before {
    content: '';
    position: absolute;
    top: 0;
    left: 0;
    right: 0;
    bottom: 0;
    background: linear-gradient(135deg, rgba(255, 255, 255, 0.1) 0%, rgba(255, 255, 255, 0.05) 100%);
    pointer-events: none;
    z-index: 0;
}

.table tbody td {
    background: transparent !important;
    border-color: rgba(255, 255, 255, 0.1) !important;
    color: #1C1C1E !important;
    transition: var(--transition) !important;
}

.table tbody tr:hover {
    background: rgba(255, 255, 255, 0.1) !important;
    transition: var(--transition) !important;
}

/* 液态玻璃徽章 */
.badge {
    backdrop-filter: var(--glass-blur-light) !important;
    -webkit-backdrop-filter: var(--glass-blur-light) !important;
    border: 1px solid rgba(255, 255, 255, 0.2) !important;
    font-weight: 600 !important;
    transition: var(--transition) !important;
}

.badge:hover {
    box-shadow: 0 4px 12px rgba(0, 0, 0, 0.2);
}

/* 液态玻璃按钮 */
.btn {
    backdrop-filter: var(--glass-blur-light) !important;
    -webkit-backdrop-filter: var(--glass-blur-light) !important;
    border: 1px solid rgba(255, 255, 255, 0.2) !important;
    transition: var(--transition) !important;
}

.btn:hover {
    transform: translateY(-2px);
    box-shadow: 0 8px 24px rgba(0, 0, 0, 0.15) !important;
}

/* 新建任务按钮液态玻璃效果 */
.btn-primary {
    background: rgba(255, 255, 255, 0.1) !important;
    backdrop-filter: blur(15px) !important;
    -webkit-backdrop-filter: blur(15px) !important;
    border: 1px solid rgba(255, 255, 255, 0.2) !important;
    color: #1C1C1E !important;
    padding: 0.75rem 1.5rem;
    border-radius: 10px;
    font-weight: 600;
    box-shadow: 
        0 4px 12px rgba(0, 0, 0, 0.1),
        inset 0 1px 0 rgba(255, 255, 255, 0.1) !important;
    transition: all 0.3s cubic-bezier(0.4, 0, 0.2, 1) !important;
    position: relative;
    overflow: hidden;
}

.btn-primary::before {
    content: '';
    position: absolute;
    top: 0;
    left: 0;
    right: 0;
    bottom: 0;
    background: linear-gradient(135deg, rgba(255, 255, 255, 0.1) 0%, transparent 50%);
    pointer-events: none;
    opacity: 0;
    transition: opacity 0.3s ease;
}

.btn-primary:hover {
    transform: translateY(-2px) scale(1.02);
    box-shadow: 
        0 6px 20px rgba(0, 0, 0, 0.15),
        0 4px 12px rgba(0, 0, 0, 0.1),
        inset 0 1px 0 rgba(255, 255, 255, 0.2) !important;
    border-color: rgba(255, 255, 255, 0.3) !important;
    background: rgba(255, 255, 255, 0.15) !important;
    color: #1C1C1E !important;
}

.btn-primary:hover::before {
    opacity: 1;
}

/* 暗色模式新建任务按钮 */
[data-theme="dark"] .btn-primary {
    background: rgba(0, 0, 0, 0.3) !important;
    border-color: rgba(255, 255, 255, 0.2) !important;
    color: #ffffff !important;
    box-shadow: 
        0 4px 12px rgba(0, 0, 0, 0.2),
        inset 0 1px 0 rgba(255, 255, 255, 0.1) !important;
}

[data-theme="dark"] .btn-primary::before {
    background: linear-gradient(135deg, rgba(255, 255, 255, 0.08) 0%, transparent 50%);
}

[data-theme="dark"] .btn-primary:hover {
    background: rgba(0, 0, 0, 0.4) !important;
    border-color: rgba(255, 255, 255, 0.3) !important;
    color: #ffffff !important;
    box-shadow: 
        0 6px 20px rgba(0, 0, 0, 0.3),
        0 4px 12px rgba(0, 0, 0, 0.2),
        inset 0 1px 0 rgba(255, 255, 255, 0.15) !important;
}

/* 液态玻璃标题 */
h2, h5 {
    color: #1C1C1E !important;
    text-shadow: 0 2px 4px rgba(0, 122, 255, 0.1);
}

/* 液态玻璃图标 */
.fas {
    filter: drop-shadow(0 2px 4px rgba(0, 0, 0, 0.1));
    transition: var(--transition);
}

.card:hover .fas {
    filter: drop-shadow(0 4px 8px rgba(0, 0, 0, 0.2));
}

/* 液态玻璃空状态 */
.text-center.py-5 {
    background: rgba(255, 255, 255, 0.05);
    backdrop-filter: var(--glass-blur-light);
    -webkit-backdrop-filter: var(--glass-blur-light);
    border-radius: var(--border-radius);
    border: 1px solid var(--glass-border);
    margin: 1rem 0;
}

/* 暗黑模式适配 */
[data-theme="dark"] .page-header {
    background: rgba(0, 0, 0, 0.3);
    border-color: rgba(255, 255, 255, 0.1);
}

[data-theme="dark"] .page-header::before {
    background: linear-gradient(135deg, rgba(255, 255, 255, 0.02) 0%, transparent 100%);
}

[data-theme="dark"] .card {
    background: rgba(0, 0, 0, 0.3) !important;
    border-color: rgba(255, 255, 255, 0.1) !important;
}

[data-theme="dark"] .card::before {
    background: linear-gradient(135deg, rgba(255, 255, 255, 0.02) 0%, transparent 100%);
}

[data-theme="dark"] .table thead th {
    background: rgba(0, 0, 0, 0.3) !important;
    color: #ffffff !important;
}

[data-theme="dark"] .table thead th::before {
    background: linear-gradient(135deg, rgba(255, 255, 255, 0.02) 0%, transparent 100%);
}

[data-theme="dark"] .table tbody td {
    color: #ffffff !important;
}

[data-theme="dark"] .table tbody tr:hover {
    background: rgba(255, 255, 255, 0.1) !important;
}

[data-theme="dark"] h2, [data-theme="dark"] h5 {
    color: #ffffff !important;
}

[data-theme="dark"] .text-center.py-5 {
    background: rgba(0, 0, 0, 0.2);
    border-color: rgba(255, 255, 255, 0.1);
}

[data-theme="dark"] .text-muted {
    color: #bdc3c7 !important;
}

/* 液态玻璃动画 */
@keyframes cardFloat {
    0%, 100% {
        transform: translateY(0);
    }
    50% {
        transform: translateY(-5px);
    }
}

.card {
    animation: cardFloat 6s ease-in-out infinite;
}

.card:nth-child(2) {
    animation-delay: 1s;
}

.card:nth-child(3) {
    animation-delay: 2s;
}

.card:nth-child(4) {
    animation-delay: 3s;
}

/* 液态玻璃响应式 */
@media (max-width: 768px) {
    .card {
        margin-bottom: 1rem;
    }
    
    .table-responsive {
        border-radius: var(--border-radius-sm);
        overflow: hidden;
    }
}
</style>

<div class="page-header">
    <div class="d-flex justify-content-between align-items-center">
        <div>
            <h2><i class="fas fa-robot me-2"></i>钉钉机器人任务管理</h2>
            <p class="text-muted mb-0">管理和监控钉钉机器人定时任务的执行状态</p>
        </div>
        <div>
            <a href="{{ url_for('add_task') }}" class="btn btn-primary">
                <i class="fas fa-plus me-1"></i>新建任务
            </a>
        </div>
    </div>
</div>

<!-- 统计卡片 -->
{% if tasks %}
<div class="row mb-4">
    <div class="col-md-3">
        <div class="card h-100 stat-card-primary">
            <div class="card-body">
                <div class="d-flex justify-content-between">
                    <div>
                        <h4 class="card-title mb-0 text-primary">{{ tasks|length }}</h4>
                        <small class="text-muted">总任务数</small>
                    </div>
                    <div class="align-self-center">
                        <i class="fas fa-tasks fa-2x text-primary"></i>
                    </div>
                </div>
            </div>
        </div>
    </div>
    <div class="col-md-3">
        <div class="card h-100 stat-card-success">
            <div class="card-body">
                <div class="d-flex justify-content-between">
                    <div>
                        <h4 class="card-title mb-0 text-success">{{ tasks|selectattr('is_active')|list|length }}</h4>
                        <small class="text-muted">已启用</small>
                    </div>
                    <div class="align-self-center">
                        <i class="fas fa-play fa-2x text-success"></i>
                    </div>
                </div>
            </div>
        </div>
    </div>
    <div class="col-md-3">
        <div class="card h-100 stat-card-warning">
            <div class="card-body">
                <div class="d-flex justify-content-between">
                    <div>
                        <h4 class="card-title mb-0 text-warning">{{ tasks|selectattr('status', 'equalto', 'running')|list|length }}</h4>
                        <small class="text-muted">运行中</small>
                    </div>
                    <div class="align-self-center">
                        <i class="fas fa-spinner fa-2x text-warning"></i>
                    </div>
                </div>
            </div>
        </div>
    </div>
    <div class="col-md-3">
        <div class="card h-100 stat-card-info">
            <div class="card-body">
                <div class="d-flex justify-content-between">
                    <div>
                        <h4 class="card-title mb-0 text-info">{{ tasks|selectattr('last_run_status', 'equalto', '成功')|list|length }}</h4>
                        <small class="text-muted">最近成功</small>
                    </div>
                    <div class="align-self-center">
                        <i class="fas fa-check-circle fa-2x text-info"></i>
                    </div>
                </div>
            </div>
        </div>
    </div>
</div>
{% endif %}

<!-- 任务列表 -->
<div class="card">
    <div class="card-header">
        <h5 class="mb-0"><i class="fas fa-robot me-2"></i>钉钉机器人任务列表</h5>
    </div>
    <div class="card-body">
        {% if tasks %}
        <div class="table-responsive">
            <table class="table table-hover table-sm">
                <style>
                    .table-sm td, .table-sm th {
                        padding: 0.3rem 0.5rem;
                        font-size: 0.875rem;
                        line-height: 1.1;
                    }
                    .table-sm .badge {
                        font-size: 0.75rem;
                        padding: 0.25rem 0.5rem;
                    }
                    .table-sm code {
                        font-size: 0.8rem;
                        white-space: nowrap;
                        overflow: hidden;
                        text-overflow: ellipsis;
                        max-width: 120px;
                        display: inline-block;
                    }
                    .table-sm .btn-sm {
                        padding: 0.25rem 0.5rem;
                        font-size: 0.75rem;
                    }
                    .table-sm .btn-group-sm > .btn {
                        padding: 0.25rem 0.5rem;
                        font-size: 0.75rem;
                    }
                </style>
                <thead>
                    <tr>
                        <th>任务名称</th>
                        <th>脚本</th>
                        <th>关联机器人</th>
                        {% if current_user.is_administrator() %}
                        <th>归属用户</th>
                        {% endif %}
                        <th>执行计划</th>
                        <th>下次执行</th>
                        <th>状态</th>
                        <th>上次执行</th>
                        <th>执行结果</th>
                        <th>操作</th>
                    </tr>
                </thead>
                <tbody>
                    {% for task in tasks %}
                    <tr data-task-id="{{ task.id }}" data-task-type="{{ task.type }}">
                        <td>
                            <strong>{{ task.name }}</strong>
                            {% if task.description %}
                            <br><small class="text-muted">{{ task.description }}</small>
                            {% endif %}
                        </td>
                        <td>
                            <span class="badge bg-secondary">{{ task.script_path.split('/')[-1] }}</span>
                        </td>
                        <td>
                            {% if task.robots %}
                                {% for robot in task.robots %}
                                    <span class="badge bg-info me-1">{{ robot.name }}</span>
                                {% endfor %}
                            {% else %}
                                <span class="text-muted">无</span>
                            {% endif %}
                        </td>
                        {% if current_user.is_administrator() %}
                        <td>
                            {% if task.user %}
                                <span class="badge bg-secondary">{{ task.user.username }}</span>
                            {% else %}
                                <span class="text-muted">未知用户</span>
                            {% endif %}
                        </td>
                        {% endif %}
                        <td>
                            <code title="{{ task.cron_expression }}">{{ task.cron_expression }}</code>
                        </td>
                        <td class="next-run-time">
                            {% if task.is_active and task.cron_expression %}
                                {% if task.next_run_time %}
                                    {{ task.next_run_time.strftime('%Y-%m-%d %H:%M:%S') }}
                                {% else %}
                                    <!-- 使用后端计算的值，避免在前端计算 -->
                                    <span title="任务已激活，等待下次执行">{{ task.next_run_time or '计算中...' }}</span>
                                {% endif %}
                            {% else %}
                                <span class="text-muted">未激活</span>
                            {% endif %}
                        </td>
                        <td class="task-status">
                            {% if not task.is_active %}
                                <span class="badge bg-secondary">已禁用</span>
                            {% elif task.status == 'running' %}
                                <span class="badge bg-warning">运行中</span>
                            {% else %}
                                <span class="badge bg-success">已启用</span>
                            {% endif %}
                        </td>
                        <td class="last-run-time">
                            {% if task.last_run_time %}
                                {{ task.last_run_time.strftime('%Y-%m-%d %H:%M:%S') }}
                            {% else %}
                                无
                            {% endif %}
                        </td>
                        <td class="task-result">
                            {% if task.last_run_status %}
                                {% if task.last_run_status == '成功' %}
                                    <span class="badge bg-success">{{ task.last_run_status }}</span>
                                {% else %}
                                    <span class="badge bg-danger">{{ task.last_run_status }}</span>
                                {% endif %}
                            {% else %}
                                <span class="badge bg-light text-dark">无</span>
                            {% endif %}
                        </td>
                        <td>
                            <div class="d-flex flex-column gap-1">
                                <!-- 第一行按钮 -->
                                <div class="btn-group btn-group-sm" role="group">
                                    {% if task.status == 'running' %}
                                        <button onclick="stopTask({{ task.id }})" 
                                                class="btn btn-outline-danger btn-sm" title="停止任务">
                                            <i class="fas fa-stop"></i>
                                        </button>
                                    {% else %}
                                        <button onclick="runTask({{ task.id }})" 
                                                class="btn btn-outline-primary btn-sm" title="立即执行">
                                            <i class="fas fa-play"></i>
                                        </button>
                                    {% endif %}
                                    <a href="{{ url_for('edit_task', task_id=task.id) }}" 
                                       class="btn btn-outline-warning btn-sm" title="编辑任务">
                                        <i class="fas fa-edit"></i>
                                    </a>
                                    <a href="{{ url_for('task_logs_page', task_id=task.id) }}" 
                                       class="btn btn-outline-info btn-sm" title="查看日志">
                                        <i class="fas fa-eye"></i>
                                    </a>
                                </div>
                                <!-- 第二行按钮 -->
                                <div class="btn-group btn-group-sm" role="group">
                                    <a href="{{ url_for('toggle_task', task_id=task.id) }}" 
                                       class="btn btn-outline-{% if task.is_active %}danger{% else %}success{% endif %} btn-sm" 
                                       title="{% if task.is_active %}暂停任务{% else %}启用任务{% endif %}">
                                        <i class="fas fa-{% if task.is_active %}pause{% else %}play{% endif %}"></i>
                                    </a>
                                    <button onclick="deleteTask({{ task.id }}, '{{ task.name }}')" 
                                            class="btn btn-outline-danger btn-sm" title="删除任务">
                                        <i class="fas fa-trash"></i>
                                    </button>
                                </div>
                            </div>
                        </td>
                    </tr>
                    {% endfor %}
                </tbody>
            </table>
        </div>
        {% else %}
        <div class="text-center py-5">
            <i class="fas fa-robot fa-3x text-muted mb-3"></i>
            <h5 class="text-muted">暂无钉钉机器人任务</h5>
            <p class="text-muted">点击上方"新建任务"按钮开始创建您的第一个钉钉机器人任务</p>
        </div>
        {% endif %}
    </div>
</div>

<!-- 快速操作面板 -->
{% if tasks %}
{# 快速操作整块已删除 #}
{% endif %}

<script>
function batchToggle(enable) {
    const action = enable ? '启用' : '暂停';
    if (confirm(`确定要${action}所有任务吗？`)) {
        // 这里可以添加批量操作的AJAX请求
        alert('批量操作功能开发中...');
    }
}

// 执行任务
function runTask(taskId) {
        console.log('开始执行任务:', taskId); // 添加调试日志
        
        // 检查任务是否已禁用
        const row = document.querySelector(`tr[data-task-id="${taskId}"]`);
        if (row) {
            const statusCell = row.querySelector('.task-status');
            if (statusCell && statusCell.textContent.trim().includes('已禁用')) {
                console.error('任务已禁用，无法执行'); // 添加调试日志
                alert('任务已禁用，无法执行');
                return;
            }
        }
        
        fetch(`/api/tasks/${taskId}/run`, {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json'
            }
        })
            .then(response => {
                console.log('API响应状态:', response.status); // 添加调试日志
                return response.json();
            })
            .then(data => {
                console.log('API响应数据:', data); // 添加调试日志
                if (data.success) {
                    // 更新按钮状态
                    updateTaskButton(taskId, 'running');
                    console.log('任务执行成功，状态已更新'); // 添加调试日志
                    // 不显示成功提示
                } else if (data.status === 'success') {
                    // 处理web_service.py返回的成功格式
                    updateTaskButton(taskId, 'running');
                    console.log('任务执行成功，状态已更新'); // 添加调试日志
                    // 不显示成功提示
                } else {
                    console.error('任务执行失败:', data); // 添加调试日志
                    alert('执行失败: ' + (data.message || data.error || '未知错误'));
                }
            })
            .catch(error => {
                console.error('网络错误:', error); // 添加调试日志
                alert('执行失败，请稍后重试');
            });
}

// 停止任务
function stopTask(taskId) {
    if (confirm('确定要停止这个任务吗？')) {
        console.log('开始停止任务:', taskId); // 添加调试日志
        fetch(`/api/tasks/${taskId}/stop`, {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json'
            }
        })
            .then(response => {
                console.log('停止任务API响应状态:', response.status); // 添加调试日志
                return response.json();
            })
            .then(data => {
                console.log('停止任务API响应数据:', data); // 添加调试日志
                if (data.status === 'success') {
                    // 更新按钮状态
                    updateTaskButton(taskId, 'pending');
                    // 不显示成功提示
                } else {
                    console.error('停止任务失败:', data); // 添加调试日志
                    alert('停止失败: ' + (data.message || data.error || '未知错误'));
                }
            })
            .catch(error => {
                console.error('停止任务网络错误:', error); // 添加调试日志
                alert('停止失败，请稍后重试');
            });
    }
}

// 删除任务
function deleteTask(taskId, taskName) {
    if (confirm(`确定要删除任务"${taskName}"吗？\n\n删除后无法恢复，请谨慎操作！`)) {
        console.log('开始删除任务:', taskId, taskName); // 添加调试日志
        fetch(`/delete_task/${taskId}`, {
            method: 'POST', // 使用POST方法，因为这是一个修改操作
            headers: {
                'Content-Type': 'application/json',
                'X-Requested-With': 'XMLHttpRequest' // 添加AJAX标识
            }
        })
            .then(response => {
                console.log('删除任务API响应状态:', response.status, '是否重定向:', response.redirected); // 添加调试日志
                if (response.redirected) {
                    // 如果服务器返回重定向，说明删除成功
                    window.location.href = response.url; // 跟随重定向
                } else if (response.ok) {
                    // 如果响应成功但没有重定向
                    window.location.reload(); // 刷新页面
                    return null;
                } else {
                    return response.text(); // 获取错误信息
                }
            })
            .then(data => {
                if (data) {
                    console.error('删除任务失败:', data); // 添加调试日志
                    alert('删除失败: ' + data);
                }
            })
            .catch(error => {
                console.error('删除任务网络错误:', error); // 添加调试日志
                alert('删除失败，请稍后重试');
            });
    }
}

// 更新任务按钮状态
function updateTaskButton(taskId, status, taskType = null) {
    let row;
    if (taskType) {
        row = document.querySelector(`tr[data-task-id="${taskId}"][data-task-type="${taskType}"]`);
    } else {
        row = document.querySelector(`tr[data-task-id="${taskId}"]`);
    }
    if (!row) return;
    
    const buttonCell = row.querySelector('.d-flex.flex-column');
    const statusCell = row.querySelector('.task-status');
    
    // 获取任务名称
    const taskNameCell = row.querySelector('td:first-child strong');
    const taskName = taskNameCell ? taskNameCell.textContent : '任务';
    
    if (status === 'running') {
        // 更新状态显示
        statusCell.innerHTML = '<span class="badge bg-warning">运行中</span>';
        
        // 更新按钮
        buttonCell.innerHTML = `
            <div class="d-flex flex-column gap-1">
                <!-- 第一行按钮 -->
                <div class="btn-group btn-group-sm" role="group">
                    <button onclick="stopTask(${taskId})" class="btn btn-outline-danger btn-sm" title="停止任务">
                        <i class="fas fa-stop"></i>
                    </button>
                    <a href="/edit_task/${taskId}" class="btn btn-outline-warning btn-sm" title="编辑任务">
                        <i class="fas fa-edit"></i>
                    </a>
                    <a href="/task_logs/${taskId}" class="btn btn-outline-info btn-sm" title="查看日志">
                        <i class="fas fa-eye"></i>
                    </a>
                </div>
                <!-- 第二行按钮 -->
                <div class="btn-group btn-group-sm" role="group">
                    <a href="/toggle_task/${taskId}" class="btn btn-outline-danger btn-sm" title="暂停任务">
                        <i class="fas fa-pause"></i>
                    </a>
                    <button onclick="deleteTask(${taskId}, '${taskName}')" class="btn btn-outline-danger btn-sm" title="删除任务">
                        <i class="fas fa-trash"></i>
                    </button>
                </div>
            </div>
        `;
    } else {
        // 更新状态显示
        statusCell.innerHTML = '<span class="badge bg-success">已启用</span>';
        
        // 更新按钮
        buttonCell.innerHTML = `
            <div class="d-flex flex-column gap-1">
                <!-- 第一行按钮 -->
                <div class="btn-group btn-group-sm" role="group">
                    <button onclick="runTask(${taskId})" class="btn btn-outline-primary btn-sm" title="立即执行">
                        <i class="fas fa-play"></i>
                    </button>
                    <a href="/edit_task/${taskId}" class="btn btn-outline-warning btn-sm" title="编辑任务">
                        <i class="fas fa-edit"></i>
                    </a>
                    <a href="/task_logs/${taskId}" class="btn btn-outline-info btn-sm" title="查看日志">
                        <i class="fas fa-eye"></i>
                    </a>
                </div>
                <!-- 第二行按钮 -->
                <div class="btn-group btn-group-sm" role="group">
                    <a href="/toggle_task/${taskId}" class="btn btn-outline-${task.is_active ? 'danger' : 'success'} btn-sm" title="${task.is_active ? '暂停任务' : '启用任务'}">
                        <i class="fas fa-${task.is_active ? 'pause' : 'play'}"></i>
                    </a>
                    <button onclick="deleteTask(${taskId}, '${taskName}')" class="btn btn-outline-danger btn-sm" title="删除任务">
                        <i class="fas fa-trash"></i>
                    </button>
                </div>
            </div>
        `;
    }
}

// 格式化时间函数，只显示到秒
function formatTime(timeString) {
    if (!timeString || timeString === '无') {
        return '无';
    }
    
    try {
        console.log('格式化时间输入:', timeString, '类型:', typeof timeString);
        // 如果是ISO格式的时间字符串，转换为本地时间
        const date = new Date(timeString);
        console.log('解析后的日期对象:', date, '是否有效:', !isNaN(date.getTime()));
        if (isNaN(date.getTime())) {
            return timeString; // 如果解析失败，返回原字符串
        }
        
        // 格式化为 YYYY-MM-DD HH:MM:SS
        const year = date.getFullYear();
        const month = String(date.getMonth() + 1).padStart(2, '0');
        const day = String(date.getDate()).padStart(2, '0');
        const hours = String(date.getHours()).padStart(2, '0');
        const minutes = String(date.getMinutes()).padStart(2, '0');
        const seconds = String(date.getSeconds()).padStart(2, '0');
        
        const formatted = `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`;
        console.log('格式化后的时间:', formatted);
        return formatted;
    } catch (error) {
        console.error('时间格式化错误:', error);
        return timeString; // 如果出错，返回原字符串
    }
}

// 定时刷新任务状态
function updateTaskStatus() {
    fetch(`{{ url_for('get_task_statuses') }}`)
        .then(response => {
            if (!response.ok) {
                throw new Error('获取任务状态失败');
            }
            return response.json();
        })
        .then(data => {
            console.log('获取到的任务状态数据:', data); // 添加调试日志
            data.forEach(task => {
                console.log(`处理任务 ${task.id}:`, task); // 添加任务处理日志
                const row = document.querySelector(`tr[data-task-id="${task.id}"][data-task-type="${task.type}"]`);
                console.log(`查找任务行 ${task.id} (${task.type}):`, row); // 添加行查找日志
                if (row) {
                    // 更新状态列
                    const statusCell = row.querySelector('.task-status');
                    console.log(`状态单元格 ${task.id}:`, statusCell); // 添加状态单元格日志
                    if (statusCell) {
                        if (!task.is_active) {
                            statusCell.innerHTML = '<span class="badge bg-secondary">已禁用</span>';
                            console.log(`任务 ${task.id} 状态更新为: 已禁用`);
                        } else if (task.status === 'running') {
                            statusCell.innerHTML = '<span class="badge bg-warning">运行中</span>';
                            console.log(`任务 ${task.id} 状态更新为: 运行中`);
                        } else {
                            statusCell.innerHTML = '<span class="badge bg-success">已启用</span>';
                            console.log(`任务 ${task.id} 状态更新为: 已启用`);
                        }
                    }
                    
                    // 更新执行结果列
                    const resultCell = row.querySelector('.task-result');
                    if (resultCell) {
                        if (task.last_run_status && task.last_run_status !== '无') {
                            if (task.last_run_status === '成功') {
                                resultCell.innerHTML = '<span class="badge bg-success">成功</span>';
                            } else {
                                resultCell.innerHTML = '<span class="badge bg-danger">失败</span>';
                            }
                        } else {
                            resultCell.innerHTML = '<span class="badge bg-light text-dark">无</span>';
                        }
                    }
                    
                    // 更新上次运行时间 - 使用格式化函数
                    const lastRunCell = row.querySelector('.last-run-time');
                    if (lastRunCell) {
                        lastRunCell.textContent = formatTime(task.last_run_time);
                    }
                    
                    // 更新下次执行时间 - 使用格式化函数
                    const nextRunCell = row.querySelector('.next-run-time');
                    if (nextRunCell) {
                        nextRunCell.textContent = formatTime(task.next_run_time);
                    }
                    
                    // 更新按钮状态
                    const buttonCell = row.querySelector('.d-flex.flex-column');
                    if (buttonCell) {
                        // 获取任务名称
                        const taskNameCell = row.querySelector('td:first-child strong');
                        const taskName = taskNameCell ? taskNameCell.textContent : '任务';
                        
                        if (task.status === 'running') {
                            buttonCell.innerHTML = `
                                <div class="d-flex flex-column gap-1">
                                    <!-- 第一行按钮 -->
                                    <div class="btn-group btn-group-sm" role="group">
                                        <button onclick="stopTask(${task.id})" class="btn btn-outline-danger btn-sm" title="停止任务">
                                            <i class="fas fa-stop"></i>
                                        </button>
                                        <a href="/edit_task/${task.id}" class="btn btn-outline-warning btn-sm" title="编辑任务">
                                            <i class="fas fa-edit"></i>
                                        </a>
                                        <a href="/task_logs/${task.id}" class="btn btn-outline-info btn-sm" title="查看日志">
                                            <i class="fas fa-eye"></i>
                                        </a>
                                    </div>
                                    <!-- 第二行按钮 -->
                                    <div class="btn-group btn-group-sm" role="group">
                                        <a href="/toggle_task/${task.id}" class="btn btn-outline-danger btn-sm" title="暂停任务">
                                            <i class="fas fa-pause"></i>
                                        </a>
                                        <button onclick="deleteTask(${task.id}, '${taskName}')" class="btn btn-outline-danger btn-sm" title="删除任务">
                                            <i class="fas fa-trash"></i>
                                        </button>
                                    </div>
                                </div>
                            `;
                        } else {
                            buttonCell.innerHTML = `
                                <div class="d-flex flex-column gap-1">
                                    <!-- 第一行按钮 -->
                                    <div class="btn-group btn-group-sm" role="group">
                                        <button onclick="runTask(${task.id})" class="btn btn-outline-primary btn-sm" title="立即执行">
                                            <i class="fas fa-play"></i>
                                        </button>
                                        <a href="/edit_task/${task.id}" class="btn btn-outline-warning btn-sm" title="编辑任务">
                                            <i class="fas fa-edit"></i>
                                        </a>
                                        <a href="/task_logs/${task.id}" class="btn btn-outline-info btn-sm" title="查看日志">
                                            <i class="fas fa-eye"></i>
                                        </a>
                                    </div>
                                    <!-- 第二行按钮 -->
                                    <div class="btn-group btn-group-sm" role="group">
                                        <a href="/toggle_task/${task.id}" class="btn btn-outline-${task.is_active ? 'danger' : 'success'} btn-sm" title="${task.is_active ? '暂停任务' : '启用任务'}">
                                            <i class="fas fa-${task.is_active ? 'pause' : 'play'}"></i>
                                        </a>
                                        <button onclick="deleteTask(${task.id}, '${taskName}')" class="btn btn-outline-danger btn-sm" title="删除任务">
                                            <i class="fas fa-trash"></i>
                                        </button>
                                    </div>
                                </div>
                            `;
                        }
                    }
                }
            });
        })
        .catch(error => {
            console.error('获取任务状态出错:', error);
        });
}

// 更新当前时间
function updateCurrentTime() {
    const now = new Date();
    const timeString = now.toLocaleTimeString('zh-CN', { 
        hour12: false,
        hour: '2-digit',
        minute: '2-digit',
        second: '2-digit'
    });
    const timeElement = document.getElementById('current-time');
    if (timeElement) {
        timeElement.textContent = timeString;
    }
}

// 页面加载完成后初始化
window.onload = function() {
    console.log('页面加载完成，初始化任务状态');
    updateTaskStatus();
    // 每秒更新一次任务状态
    setInterval(updateTaskStatus, 1000);
    // 每秒更新时间
    setInterval(updateCurrentTime, 1000);
    updateCurrentTime(); // 立即更新一次
};

// 自动刷新页面以更新下次执行时间（每分钟刷新一次）
setTimeout(function() {
    location.reload();
}, 60000);
</script>
{% endblock %}